package com.graduate.nixingpotterty.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.graduate.nixingpotterty.entity.Users;
import com.graduate.nixingpotterty.service.IUsersService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ZhengHao
 * @since 2025-01-12
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/users")
public class UsersController {

    private final IUsersService usersService;

    // 添加用户 (Create)
    @PostMapping
    public boolean addUser(@RequestBody Users user) {
        return usersService.customAddUser(user);
    }

    // 删除用户 (Delete)
    @DeleteMapping("/{userId}")
    public boolean deleteUserById(@PathVariable Long userId) {
        return usersService.customDeleteUserById(userId);
    }

    // 更新用户信息 (Update)
    @PutMapping
    public boolean updateUser(@RequestBody Users user) {
        return usersService.customUpdateUser(user);
    }

    // 根据ID查询用户 (Read by ID)
    @GetMapping("/{userId}")
    public Users getUserById(@PathVariable Long userId) {
        return usersService.customGetUserById(userId);
    }

    // 查询所有用户 (Read all)
    @GetMapping
    public List<Users> listUsers() {
        return usersService.customListUsers();
    }

    // 根据条件查询用户 (Conditional Read)
    @GetMapping("/search")
    public List<Users> getUsersByConditions(
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String email) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        if (username != null && !username.isEmpty()) {
            queryWrapper.eq("username", username);
        }
        if (email != null && !email.isEmpty()) {
            queryWrapper.eq("email", email);
        }
        return usersService.list(queryWrapper);
    }

    /**
     * 用户注册接口
     */
    @PostMapping("/register")
    public ResponseEntity<String> registerUser(@RequestBody Users user) {
        boolean result = usersService.registerUser(user);
        if (result) {
            return ResponseEntity.ok("注册成功");
        } else {
            return ResponseEntity.badRequest().body("用户名已存在");
        }
    }

    /**
     * 用户登录接口
     */
    @PostMapping("/login")
    public ResponseEntity<String> loginUser(@RequestParam("username") String username,
                                            @RequestParam("password") String password) {
        boolean isAuthenticated = usersService.loginUser(username, password);
        if (isAuthenticated) {
            return ResponseEntity.ok("登录成功");
        } else {
            return ResponseEntity.status(401).body("用户名或密码错误");
        }
    }
}
